<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ $t('login.form.title') }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      size="large"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username"
          :placeholder="$t('login.form.userName.placeholder')">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label>
        <a-input-password
          v-model="userInfo.password"
          :placeholder="$t('login.form.password.placeholder')"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item
        field="smsCode"
        :rules="[{ required: true, message: '验证码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label>
        <a-space>
          <a-input v-model="userInfo.smsCode"
            placeholder="请输入验证码">
            <template #prefix>
              <icon-safe />
            </template>
          </a-input>
          <a-button type="primary"
           @click="sendMsgCode" 
           :loading="msgLoading">
              获取短信
          </a-button>
        </a-space>
      </a-form-item>

      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword">
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
          <a-link>{{ $t('login.form.forgetPassword') }}</a-link>
        </div>
        <a-button type="primary" html-type="submit" 
          long size="large" :loading="loading">
          {{ $t('login.form.login') }}
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { encrypt, decrypt } from '@/utils/jsencrypt'
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore , useDictStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { getSmsCode } from '@/api/user'
  import type { LoginData, SmsCode, SmsCodeRes } from '@/api/user';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const dictStore = useDictStore();
  let msgLoading = ref(false);
  let loginForm = ref();

  const loginConfig = useStorage('login-config', {
      rememberPassword: false,
      username: '',
      password: '',
  });
  const userInfo = reactive({
    smsCode: '',
    username: loginConfig.value.username 
    ? decrypt(loginConfig.value.username) 
    : loginConfig.value.username,
    password: loginConfig.value.password
    ? decrypt(loginConfig.value.password) 
    : loginConfig.value.password,
  });

  const sendMsgCode = async () => {
    if(!checkField()){ return }
    try {
      msgLoading.value = true;
      getSmsCode({
        username: userInfo.username,
        password: userInfo.password
      }).then((res: any)=>{
        Message.success(res.msg);
      })
    } catch (err) {
      errorMessage.value = (err as Error).message;
    } finally {
      msgLoading.value = false;
    }
  }

  const checkField = () : boolean =>{
     if(userInfo?.username?.replace(/\s/g, '') == ''
      && userInfo?.password?.replace(/\s/g, '') == ''){
        loginForm.value.setFields({ 
          username: { 
              status: 'error', 
              message: '用户名不能为空'
          },
          password: { 
              status: 'error', 
              message: '密码不能为空'
          }
        });
        return false;
     } else if(userInfo?.username?.replace(/\s/g, '') == ''){
        loginForm.value.setFields({ username: { 
          status: 'error', message: '用户名不能为空'
        }});
        return false;
      } else if(userInfo?.password?.replace(/\s/g, '') == '') {
        loginForm.value.setFields({ password: { 
          status: 'error', message: '密码不能为空'
        }});
        return false;
      }

     return true;
  }

  const handleSubmit = async ({errors,values }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login(values as LoginData);
        await dictStore.getDictConfig(); // 获取全部字典表数据
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          name: (redirect as string) || 'Workplace',
          query: { ...othersQuery },
        });
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        if(rememberPassword){
          loginConfig.value.username = encrypt(username) as string;
          loginConfig.value.password = encrypt(password) as string;
        }
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
      text-align: center;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
